package event

import (
	models2 "beergo/app/admin/models"
	"beergo/app/check/models"
	"beergo/app/check/services"
	models3 "beergo/app/chinamap/models"
	"beergo/lib/event"
	"beergo/lib/tool"
	"github.com/beego/beego/v2/server/web/context"
)

func init() {
	event.ListenJoin("check.AfterServiceCreate check.AfterServiceUpdate", func(v interface{}, ctx *context.Context) {
		model,ok:=v.(*models.Service)
		if ok {
			//创建或者更新地理位置信息
			println(model.Id)
			services.UpdateOrInsertService(*model)
		}
	})
	event.ListenJoin("check.AfterTaskCreate check.AfterTaskUpdate", func(v interface{}, ctx *context.Context) {
		model,ok:=v.(*models.Task)
		if ok {
			//创建或者更新地理位置信息
			println(model.Id)
			services.UpdateOrInsertTask(*model)
		}
	})
	event.ListenJoin("check.AfterOrgUpdate", func(v interface{}, ctx *context.Context) {
		model,ok:=v.(*models.Org)
		if ok {
			//创建或者更新地理位置信息
			println(model.Id)
			services.UpdateOrInsertOrg(*model)
			//审核认证后检查是否创建了后台登录的账号
			repAdminUser:=models2.AdminUserRepository{}
			adminUsers,_:=repAdminUser.FindBy(tool.M{"uid":model.User.Id},nil,0,0)
			var adminUser models2.AdminUser
			if len(adminUsers) > 1 {
				for _, adminUser := range adminUsers {
					adminUser.Delete()
				}
			}else if len(adminUsers) == 0 {
				adminUser = *new(models2.AdminUser)
				model.Load("User")
				adminUser.Account =  model.User.Phone
				adminUser.Password =  model.User.Password
				adminUser.Uid = model.User.Id
				adminUser.FillList("groups",[]int{2})
				adminUser.Save()
			}else {
				adminUser = adminUsers[0]
				adminUser.Account =  model.User.Phone
				adminUser.Password =  model.User.Password
				adminUser.Uid = model.User.Id
				adminUser.FillList("groups",[]int{2})
				adminUser.Save()
			}

			//补充位置信息到area
			repMap := models3.ChinaAreaRepository{}
			areas,_:=repMap.FindBy(tool.M{"code__in":[]string{model.Province,model.City,model.District}},[]string{"code"},0,0)
			model.Area = ""
			for i, area := range areas {
				if i>0 {
					model.Area += ","
				}
				model.Area += area.Name
			}
			model.SetEventOff()
			model.Save()

		}
	})
	event.ListenJoin("check.AfterOrgCreate", func(v interface{}, ctx *context.Context) {
		model,ok:=v.(*models.Org)
		if ok {
			model.Status = &models.OrgStatus{Id: 1}
			model.SetEventOff()
			model.Save()
		}
	})
}
